package com.hxqc.nc.report.web.configure;

import com.hxqc.nc.report.core.nc.sys.model.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptorAdapter;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
import org.springframework.web.socket.handler.WebSocketHandlerDecorator;
import org.springframework.web.socket.handler.WebSocketHandlerDecoratorFactory;


/**
 * stomp websocket的子协议，stomp: simple/streaming text oriented message protocol. 简单/流 文本消息协议,
 * 选择使用内存中级,还是使用activeMQ等中间件服务器
 *
 * @author leihz
 * @date 2017/7/20 11:20
 * @desc 123
 */
//@Configuration
//@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    private Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 连接的端点，客户端建立连接时需要连接这里配置的端点
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/nc-report-user")
                // 在握手时就获得user，判断是否登录。
                .addInterceptors(new WebSocketHandshakeInterceptor())
                .setHandshakeHandler(new MyHandshakeHandler())
                .withSockJS();
    }

    /**
     * applicationDestinationPrefixes应用前缀，所有请求的消息将会路由到@MessageMapping的controller上，
     * enableStompBrokerRelay是代理前缀，而返回的消息将会路由到代理上，所有订阅该代理的将收到响应的消息。
     *
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry messageBrokerRegistry) {
        //messageBrokerRegistry.setApplicationDestinationPrefixes("/app");
        messageBrokerRegistry.enableSimpleBroker("/topic", "/queue");
    }

    /**
     * 输入通道参数设置
     */
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.setInterceptors(new ChannelInterceptorAdapter() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                //System.out.println("recv : "+message);
                StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
                SysUser user = (SysUser)accessor.getSessionAttributes().get("user");
                return super.preSend(message, channel);
            }
        });
        //线程信息
       // registration.taskExecutor().corePoolSize(4).maxPoolSize(8).keepAliveSeconds(60);
    }

    /**
     * 输出通道参数配置
     */
    @Override
    public void configureClientOutboundChannel(ChannelRegistration registration) {
        registration.setInterceptors(new ChannelInterceptorAdapter() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
               // System.out.println("send: "+message);
                return super.preSend(message, channel);
            }
        });

        //线程信息
       // registration.taskExecutor().corePoolSize(4).maxPoolSize(8);
    }

    /**
     * 消息传输参数配置
     */
    @Override
    public void configureWebSocketTransport(final WebSocketTransportRegistration registration) {
        registration.addDecoratorFactory(new WebSocketHandlerDecoratorFactory() {
            @Override
            public WebSocketHandler decorate(final WebSocketHandler handler) {
                return new WebSocketHandlerDecorator(handler) {
                    @Override
                    public void afterConnectionEstablished(final WebSocketSession session) throws Exception {
                        String username = session.getPrincipal().getName();
                        log.info("用户: " + username+"  " +
                                "上线了!");
                        super.afterConnectionEstablished(session);
                    }

                    @Override
                    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus)
                            throws Exception {
                        String username = session.getPrincipal().getName();
                        log.info("用户: " + username+"  下线了!");
                        super.afterConnectionClosed(session, closeStatus);
                    }
                };
            }
        });
        super.configureWebSocketTransport(registration);
    }
}
